<template>
  <div class="container-box" style="height: calc(-114px + 100vh)">
    <div class="header">
      <div>
        <el-button @click="back" :icon="Back">返回</el-button>
      </div>
      <div>
        <el-button @click="preview">预览</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </div>

    <!-- 表单预览 -->
    <FormRender v-model="openPreview" :formSetting="formSetting" :operateType="'preview'" :data="data" />

    <!-- 表单设计 -->
    <DesignForm :formSetting="formSetting" />
  </div>
</template>

<script setup lang="ts">
import { Back } from "@element-plus/icons-vue";
import DesignFormApi, { DesignFormEdit } from '@/api/design/designForm';
import { FormSetting } from '@/components/DesignForm';
import successMsg from '@/utils/successMsg';

const formSetting = ref<FormSetting>({
  name: '未命名的表单',
  formConfig: {},
  formStyle: {
    inline: false,
    labelPosition: 'left',
    labelWidth: 'auto',
    labelSuffix: '',
    hideRequiredAsterisk: false,
    requireAsteriskPosition: 'right',
    showMessage: true,
    inlineMessage: false,
    statusIcon: false,
    disabled: false,
    validateOnRuleChange: true,
    scrollToError: false
  },
  formItemList: [],
});

const data = ref<DesignFormEdit>({});
const submit = async () => {
  Object.assign(data.value, formSetting.value);
  data.value.formConfig = JSON.stringify(formSetting.value.formConfig);
  data.value.formItemList = JSON.stringify(formSetting.value.formItemList);
  data.value.formStyle = JSON.stringify(formSetting.value.formStyle);
  const { success, message } = await DesignFormApi[type.value](data.value);
  successMsg(success, message);
}

const openPreview = ref(false);
//预览
const preview = () => {
  openPreview.value = true;
}

const router = useRouter(); //实例化路由
//返回
const back = () => {
  router.push('/design/designform');
}

const type = ref<string>();
const route = useRoute(); //实例化路由
onMounted(async () => {
  const id = route.params.id as string;
  type.value = route.params.type as string;
  // 根据ID获取数据
  if (type.value === 'update') {
    const data = await DesignFormApi.details(id);
    Object.assign(formSetting.value, data);
    formSetting.value.formConfig = JSON.parse(data.formConfig);
    formSetting.value.formItemList = JSON.parse(data.formItemList);
    formSetting.value.formStyle = JSON.parse(data.formStyle);
  }
})
</script>

<style lang="scss" scoped>
.container-box {
  background-color: white;
  display: flex;
  flex-direction: column;
  border: 1px solid var(--el-border-color);
}

.header {
  display: flex;
  border-bottom: 1px solid var(--el-border-color);
  padding: 10px;
  justify-content: space-between;
}
</style>
